<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use app\common\service\WXUtils;

class Adminuser extends Common
{
    public $modelDb;
    public $postDatas;

    public function _initialize()
    {
        parent::_initialize();
        $this->modelDb = model("AdminUser");
    }

    protected $beforeActionList = [
        'register_fun' => ['only' => 'register'],
    ];

    protected function register_fun()
    {
        $this->postDatas = [
            'username' => isset($this->postData['username']) ? $this->postData['username'] : '',
            'password' => isset($this->postData['password']) ? $this->postData['password'] : '',
            'realname' => isset($this->postData['realname']) ? $this->postData['realname'] : '',
            'phone' => isset($this->postData['phone']) ? $this->postData['phone'] : '',
            'phonecode' => isset($this->postData['phonecode']) ? $this->postData['phonecode'] : '',
            'dealerid' => isset($this->postData['storeid']) ? $this->postData['storeid'] : '',
        ];
    }
    // public function add(){
    // 	$this->postData['puserid'] = $this->uinfo['userid'];
    //        $id = $this->modelDb->save_data($this->postData);
    //        if($id === false){
    //            return $this->app_error($this->modelDb->getError());
    //        }
    //        else{
    //            $info = $this->modelDb->get_data(['item_id'=>$id]);
    //        }
    //    	return $this->app_success($info);
    //    }
    public function register()
    {
        $result = $this->validate($this->postDatas, 'AdminUser.register_new');
        if ($result !== true) {
            return $this->app_error($result);
        }
        $info = $this->modelDb->save_data_new($this->postDatas);
        if ($info === false) {
            return $this->app_error($this->modelDb->getError());
        }
        model('MemberStatistics')->add_log();
        // model("Statistics")->add_log(1);
        // model("Jifen")->save_datas(['userid'=>$id, 'taskid'=>4]);
        // $info = $this->modelDb->where('userid', $userid)->find();
        $info['token'] = model("MemberToken")->create_token($info['userid'], $info['username']);
        // // 获取并保存openid
        // $wxutils = new WXUtils();
        // $openid = $wxutils->get_wechat_openid($this->postData['code']);
        // if ($openid) {
        // 	model('AdminUser')->where('userid', $userid)->setField('openid', $openid);
        // }
        // 封装模板消息的参数
        // 获取formid
        // $this->postData['formid'] = isset($this->postData['formid']) ? $this->postData['formid'] : '';
        // $formid = $this->postData['formid'];
        // // 获取经销商名称
        // $dealername = model('AdminUser')->where('roleid', 6)->where('dealerid', $info['dealerid'])->value('fullname');
        // if ($formid != '') {
        // 	$templateMsgData = [
        // 		'openid' => $openid,
        // 		'phone' => $info['phone'],
        // 		'nickname' => $info['realname'],
        // 		'addtime' => date("Y-m-d H:i", time()),
        // 		'dealername' => $dealername,
        // 		'formid' => $formid,
        // 	];
        // 	$wxutils = new WXUtils();
        // 	$wxutils->sendRegisterTemplateMsg($templateMsgData);
        // }
        trace($info);
        return $this->app_success($info);
    }

    public function login()
    {
        $result = $this->validate($this->postData, 'AdminUser.login_phone');
        if (true !== $result) {
            return $this->app_error($result);
        }
        $phone = $this->postData['phone'];
        $password = md5($this->postData['password']);
        $id = $this->modelDb->login_phone($phone, $password);
        if ($id === false) {
            return $this->app_error("用户名/手机号/邮箱或密码输入错误！");
        }
        model("Jifen")->save_datas($id, 1);
        $mdata = $this->modelDb->get_data(['item_id' => $id]);
        $mdata['avatar'] = 'https://sijia.test.cmsthink.com/public/static/images/tm-pay-icon-wx.jpg';
        if (in_array($mdata['roleid'], [1, 4, 6])) {
            return $this->app_error('账号或密码错误');
        }
        $mdata['token'] = model("MemberToken")->create_token($id, $mdata['username']);
        $mdata['vipremind'] = 0;
        if ($mdata['vip'] && $mdata['vipendtime'] < time() + 86400 * config('VIPREMINDDAYS')) {
            $mdata['vipremind'] = 1;
        }
        // 获取并保存openid
        $wxutils = new WXUtils();
        $openid = $wxutils->get_wechat_openid($this->postData['code']);
        if ($openid) {
            model('AdminUser')->where('userid', $id)->setField('openid', $openid);
        }
        // $mdata['guanzhu'] = model('Favorites')->where('userid', $id)->where('typeid', 1)->count();
        // $mdata['favs'] = model('Favorites')->where('userid', $id)->where('typeid', 2)->count();
        // $mdata['issign'] = model('Jifen')->get_sign($id);
        // 封装模板消息的参数
        $this->postData['formid'] = isset($this->postData['formid']) ? $this->postData['formid'] : '';
        $formid = $this->postData['formid'];
        if ($formid != '') {
            $info = $this->modelDb->where('userid', $id)->find();
            $templateMsgData = [
                'openid' => $info['openid'],
                'realname' => $info['realname'],
                'logintime' => date("Y-m-d H:i", time()),
                'phone' => $info['phone'],
                'desc' => '您已成功登录斯家俱乐部小程序',
                'formid' => $this->postData['formid'],

            ];
            // $wxutils = new WXUtils();
            // $wxutils->sendWxLoginTemplateMsg($templateMsgData);
        }
        $mdata['encrypt_card_id'] = 'EnMGEvwiSZHmMZ1nBM0uG%2BMP4bhvZ6ZmyLwHlPyStU7dqnLPSBXKrMPoPV76Dsn%2B';
        $mdata['outer_str'] = '123';
        $mdata['biz'] = 'MzU1Nzg3MzU5Ng%3D%3D#wechat_redirect';
        //
        return $this->app_success($mdata);
    }

    public function editpwd()
    {
        $this->postData['phone'] = isset($this->postData['phone']) ? $this->postData['phone'] : $this->uinfo['phone'];
        $this->postData['userid'] = isset($this->uinfo['userid']) ? $this->uinfo['userid'] : 0;
        $result = $this->validate($this->postData, 'AdminUser.change_pwd');
        if ($result !== true) {
            return $this->app_error($result);
        }
        $id = $this->modelDb->forget_pwd($this->postData);
        if ($id) {
            return $this->app_success([], '修改成功');
        } else {
            return $this->app_error('修改失败');
        }
    }

    public function memberinfo()
    {
        $userid = isset($this->postData['userid']) && $this->postData['userid'] ? $this->postData['userid'] : $this->uinfo['userid'];
        $data = $this->modelDb->where('userid', $userid)->field('password,encrypt,uuid,paypassword,register_code', true)->find();
        // $data['guanzhu'] = model('Favorites')->where('userid', $userid)->where('typeid', 1)->count();
        // $data['favs'] = model('Favorites')->where('userid', $userid)->where('typeid', 2)->count();
        // $data['issign'] = model('Jifen')->get_sign($userid);
        // $data['vip'] = 1;
        $data['vipremind'] = 0;
        if ($data['vip'] && $data['vipendtime'] < time() + 86400 * config('VIPREMINDDAYS')) {
            $data['vipremind'] = 1;
        }
        return $this->app_success($data);
    }

    public function get_reginfo()
    {
        $register_code = $this->postData['register_code'];
        $data = $this->modelDb->where('register_code', $register_code)->field('userid,phone,realname,roleid,status,puserid,roleid,gender,weixin,idcard,register_code,identity')->find();
        $data['dealer'] = $data['dealer'];
        $data['prealname'] = $data['prealname'];
        $data['identity_name'] = $data['identity_name'];
        if ($data['status'] != 99) {
            return $this->app_error('该账号已经完成注册');
        }
        return $this->app_success($data);
    }

    public function update_info()
    {
        $id = $this->modelDb->update_data($this->postData);
        if ($id === false) {
            return $this->app_error($this->modelDb->getError());
        }
        return $this->app_success();
    }

    public function update()
    {
        if (!$this->postData['value']) {
            return $this->app_error('传值不能为空');
        }
        // if(isset($this->postData['field'])){
        // 	$this->postData[$this->postData['field']] = $this->postData['value'];
        // }
        // $this->postData['userid'] = $this->uinfo['userid'];
        if (in_array($this->postData['field'], ['userid', 'username', 'lastloginip', 'lastlogintime', 'jifen', 'signs', 'status', 'addtime', 'register_code', 'amount', 'dis_amount'])) {
            return $this->app_error('您选择的内容不可修改');
        }
        if (in_array($this->postData['field'], ['phone', 'idcard', 'weixin'])) {
            $count = $this->modelDb->where($this->postData['field'], $this->postData['value'])->count();
            if ($count) {
                $arr = ['phone' => '手机号', 'idcard' => '身份证号', 'weixin' => '微信号'];
                return $this->app_error('该' . $arr[$this->postData['field']] . '已存在，请重新输入');
            }
        }
        $userid = $this->modelDb->where('userid', $this->uinfo['userid'])->setField($this->postData['field'], $this->postData['value']);
        if ($userid) {
            return $this->app_success();
        } else {
            return $this->app_error();
        }
    }

    public function add_address()
    {
        $this->postData['userid'] = $this->uinfo['userid'];
        $id = model('MemberAddress')->save_data($this->postData);
        if ($id === false) {
            return $this->app_error(model('MemberAddress')->getError());
        }
        return $this->app_success();
    }

    // 获取地址列表
    public function address_list()
    {
        $userid = $this->uinfo['userid'];
        $list = model("MemberAddress")->list_data(['userid' => $userid], 0, 0, 'id, phone, consignee, city, address');
        if (!empty($list)) {
            return $this->app_success($list);
        } else {
            return $this->app_success([], '列表为空');
        }
    }

    public function update_address()
    {
        $id = model('MemberAddress')->update_data($this->postData);
        if ($id === false) {
            return $this->app_error(model('MemberAddress')->getError());
        }
        return $this->app_success();
    }

    public function del_address()
    {
        $id = model('MemberAddress')->where('id', $this->postData['id'])->delete();
        return $this->app_success();
    }

    public function add_poster()
    {
        $this->postData['userid'] = $this->uinfo['userid'];
        $this->postData['title'] = $this->postData['write_title'] ? $this->postData['write_title'] : $this->postData['select_title'];
        $this->postData['typeid'] = 1;
        $ids = model('Poster')->save_data($this->postData);
        if ($ids === false) {
            return $this->app_error(model('Poster')->getError());
        }
        return $this->app_success();
    }

    public function update_poster()
    {
        $this->postData['title'] = $this->postData['write_title'] ? $this->postData['write_title'] : $this->postData['select_title'];
        $this->postData['typeid'] = 1;
        $ids = model('Poster')->update_data($this->postData);
        if ($ids === false) {
            return $this->app_error(model('Poster')->getError());
        }
        return $this->app_success();
    }

    //保存分享截图
    public function sharethumb_add()
    {
        $this->postData['userid'] = $this->uinfo['userid'];
        $ids = model('ShareThumb')->save_data($this->postData);
        if ($ids === false) {
            return $this->app_error(model('Poster')->getError());
        }
        return $this->app_success();
    }

    //检测密码是否正确
    public function check_pwd()
    {
        $password = db('AdminUser')->where('userid', $this->uinfo['userid'])->value('password');
        if ($password != md5($this->postData['password'])) {
            return $this->app_error('密码输入错误，请重新输入');
        }
        $price = model('Convert')->where('id', $this->postData['goods_id'])->value('price');
        if ($price > $this->uinfo['jifen']) {
            return $this->app_error('积分不足，无法兑换');
        }
        return $this->app_success();
    }

    // 获取小程序码
    public function share_qrcode()
    {
        // 1、先查看此用户没有没推广二维码，如果有的话，就直接返回，没有的话，走第2步
        $mpqrcode_data = model('AdminUser')->where('userid', $this->uinfo['userid'])->value('mpqrcode');
        // $arrQR = isset($mpqrcode_data) ? $mpqrcode_data : '';
        // if ($arrQR != '') {
        // 	$arrQR = [
        // 		'qrcodeimg' => APP_URL . '/' . $mpqrcode_data,
        // 	];
        // 	return $this->app_success($arrQR);
        // }
        // 2、首先获取access_token
        $wxutils = new WXUtils();
        $access_token = $wxutils->getAccessToken();
        // return $access_token;
        // 3、获取带参数无限个数小程序码
        $dealerinfo = model('AdminUser')->where('userid', $this->uinfo['dealerid'])->where('roleid', '6')->field('userid as storeid, username, username, province_code')->find();
        // $provinceinfo = model('City')->where('code', $dealerinfo['province_code'])->value('title');
        $scene = $dealerinfo['province_code'] . ',' . $dealerinfo['storeid'];
        // if ($dealerinfo) {
        // 	$scene = [
        // 		'p_id' => $dealerinfo['province_code'],
        // 		'd_id' => $dealerinfo['storeid'],
        // 	];
        // }
        // $scene_str = json_encode($scene);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
        $arr = [
            'scene' => $scene,
            'page' => 'pages/login/register',
            'width' => 400,
            'auto_color' => false,
        ];
        $param_json = json_encode($arr);
        $data = curlPost($url, $param_json);
        // 4、将图片数据data存储到服务器并写入数据库
        $filename = md5('qrcode' . time() . rand(100, 999));
        $filepath = 'upload/4sqrcode/' . $filename . '.png';
        // trace('xxxxx');
        // trace($filepath);
        // 存储到服务器
        file_put_contents(ROOT_PATH . $filepath, $data);
        // 写入数据库
        model('AdminUser')->where('userid', $this->uinfo['userid'])->update(['mpqrcode' => $filepath]);
        // 返回给客户端
        $arrQR = [
            'qrcodeimg' => APP_URL . '/' . $filepath,
        ];
        return $this->app_success($arrQR);
        // $file = fopen('qrcode_' . time() . '.jpg', $data); //打开文件准备写入
        // fwrite($file, $res); //写入,$res为图片二进制内容
        // fclose($file); //关闭

        // return $data;
    }

    // 注销账号（所有线索及权益全部丢失）
    public function clearuser()
    {
        $pwd = md5(create_randomstr());
        model('AdminUser')->where('userid', $this->uinfo['userid'])->update(['username' => '*#*#' . $this->uinfo['username'] . '*#*#', 'phone' => '*#*#' . $this->uinfo['phone'], 'password' => $pwd]);
        return $this->app_success();
    }

    // 获取顶部滚动提示语（经纪人可看）
    public function banner_tip()
    {
        if ($this->uinfo['roleid'] == 9) {
            $content = '';
            if ($this->postData['type'] == 'xiansuo') {
                // 线索
                $content = config('SCROLL_TIP_1');
            } elseif ($this->postData['type'] == 'quanyi') {
                // 权益
                $content = config('SCROLL_TIP_2');
            }
            $data = [
                'content' => $content,
            ];
            return $this->app_success($data);
        } else {
            return $this->app_success([], '权限不足');
        }
    }

    // 获取经纪人列表
    public function getuserlist()
    {
        $dealerid = '';
        if (isset($this->postData['dealerid'])) {
            $dealerid = $this->postData['dealerid'];
        } else {
            return $this->app_success([], '请确定当前经销商');
        }
        $where = [
            'roleid' => '9',
            'dealerid' => $dealerid,
        ];
        $roleid = $this->uinfo['roleid'];
        if ($roleid == '8') { // 销售总监
            $where = ['gouchetag' => '1'];
        } else if ($roleid == '10') { // 增值总监
            $where = ['xubaotag' => '1'];
        } else if ($roleid == '11') { // 售后总监
            $where = ['baoyangtag' => '1'];
        }
        $list = model('AdminUser')->where($where)->field('userid,realname')->order('userid desc')->select();
        $all[] = [
            'userid' => '',
            'realname' => '全部成员'
        ];
        $list = array_merge($all, $list);
        return $this->app_success($list);
    }

    // 站内消息列表
    public function usermessagelist()
    {
        $tagids = model('UserTag')->where('userid', $this->uinfo['userid'])->column('tagid');
        trace($tagids);
        if ($tagids) {
            $messageids = model('TagMessage')->whereIn('tagid', $tagids)->column('messageid');
            $messagelist = model('Message')->whereIn('id', $messageids)->select();
            return $this->app_success($messagelist);
        } else {
            return $this->app_success([], '');
        }
    }

    // 获取站内行详情
    public function usermessagedetail()
    {
        $messageid = $this->postData['messageid'];
        $detail = model('Message')->where('id', $messageid)->find();
        if ($detail) {
            return $this->app_success($detail);
        } else {
            return $this->app_success([], '');
        }
    }

    // 根据手机号码查找用户
    public function searchuser()
    {
        $phone = $this->postData['phone'];
        $userinfo = model('AdminUser')->where('phone', $phone)->find();
        $dealerid = $userinfo['dealerid'];
        if ($userinfo) {
            if ($dealerid === $this->uinfo['dealerid']) {
                if ($this->uinfo['roleid'] === 11) {
                    $dealname = model('AdminUser')->where('userid', $userinfo['dealerid'])->value('realname');
                    $returnData['userid'] = $userinfo['userid'];
                    $returnData['avatar'] = $userinfo['avatar'];
                    $returnData['username'] = $userinfo['realname'];
                    $returnData['dealername'] = $dealname;
                    return $this->app_success($returnData);
                } else {
                    return $this->app_error('没有查询到此用户信息，请确定该账号有售后总监权限');
                }
            } else {
                return $this->app_error('没有查询到此用户信息，请确定该用户属于该经销商');
            }
        } else {
            return $this->app_error('没有查询到此用户信息，请核实手机号是否正确');
        }
    }

    // 升级为荣耀会员
    public function upgradevip()
    {
        $userid = $this->postData['userid'];
        $type = $this->postData['type'];
        $userinfo = model('AdminUser')->where('userid', $userid)->find();
        if ($userinfo['vip'] === 1) { // 已经是荣耀会员
            return $this->app_error('此用户已经是荣耀会员了');
        }
        if ($userinfo['vip'] === 0 && $userinfo['vipendtime'] === 0) {
            model('OrderVip')->save_order_baoyang_vip($userid, $type);
            $endtime = strtotime(date('Y-m-d', strtotime('+1 year')) . ' 23:59:59');
            model('AdminUser')->where('userid', $userid)->update(['vipendtime' => $endtime, 'vip' => 1]);
            exec_php('/index/cron/send_coupons', ['userid' => $userid, 'type' => 'vip']);
            $data = [
                'vipendtime' => date("Y-m-d", $endtime)
            ];
            return $this->app_success($data, '操作成功');
        } else {
            return $this->app_error('此用户不符合升级条件');
        }
    }
}